package com.lnsf.bookstore.web.collection.controller;

import com.alibaba.fastjson.JSONObject;
import com.lnsf.bookstore.common.annotation.IgnoreAuth;
import com.lnsf.bookstore.common.annotation.LoginUser;
import com.lnsf.bookstore.common.controller.ApiBaseAction;
import com.lnsf.bookstore.web.collection.service.ApiCollectService;
import com.lnsf.bookstore.web.collection.vo.ApiCollect;
import com.lnsf.bookstore.web.user.vo.ApiUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/collection")
public class ApiCollectController extends ApiBaseAction{

    @Autowired
    private ApiCollectService apiCollectService;

    @RequestMapping("/list")
    @ResponseBody
    public Object list(@LoginUser ApiUser loginUser) {
        JSONObject jsonObject = getJsonRequest();
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("userId",loginUser.getUserId());
        List<ApiCollect> list = apiCollectService.queryList(param);
        return toResponsSuccess(list);
    }

    /**
     * 1、给用户中心那边对收藏进行删除
     * 2、给首页中的商品进行收藏
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("/saveOrDelete")
    @ResponseBody
    public Object saveOrDelete(@LoginUser ApiUser loginUser) {
        JSONObject jsonObject = getJsonRequest();
        Integer bookId = jsonObject.getInteger("bookId");
        Map param = new HashMap();
        //param.put("userId", loginUser.getUserId());
        param.put("userId", loginUser.getUserId());
        param.put("bookId", bookId);
        List<ApiCollect> collectList = apiCollectService.queryList(param);
        Integer result = null;
        String handleType = "add";
        if(collectList == null || collectList.size()<1){
            ApiCollect apiCollect = new ApiCollect();
            apiCollect.setAddTime(new Date());
            apiCollect.setBookId(bookId);
            apiCollect.setIsAttention(0);
            apiCollect.setUserId(loginUser.getUserId());
            //apiCollect.setUserId(loginUser.getUserId());
            //添加收藏
            result = apiCollectService.insert(apiCollect);
        }else {
            //取消收藏
            result = apiCollectService.delete(collectList.get(0).getId());
            handleType = "delete";
        }
        if(result > 0){
            Map<String,Object> data = new HashMap<String, Object>();
            data.put("type", handleType);
            return toResponsSuccess(data);
        }
        return toResponsFail("操作失败");
    }



}
